/*
 * @(#)ImageUtil.java	1.0 2010-4-16
 * Copyright zhangzz,Inc. 2010 - All Rights Reserved. 
 */
package com.azaing.common.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 
 * 
 * @version 1.0 zhangzz 2010-4-16
 * @author zhangzz
 * @see
 */
public class ImageUtil {
	public static void scaleImage(InputStream imgInputStream,
			OutputStream imgOutputStream, int scale) {
		try {

			Image src = javax.imageio.ImageIO.read(imgInputStream);
			int width = (int) (src.getWidth(null) * scale / 100.0);
			int height = (int) (src.getHeight(null) * scale / 100.0);
			BufferedImage bufferedImage = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);

			bufferedImage.getGraphics().drawImage(
					src.getScaledInstance(width, height, Image.SCALE_SMOOTH),
					0, 0, null);
			JPEGImageEncoder encoder = JPEGCodec
					.createJPEGEncoder(imgOutputStream);
			encoder.encode(bufferedImage);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void scaleImage(String imgSrc, String imgDist, int scale) {
		try {
			File file = new File(imgSrc);
			if (!file.exists()) {
				return;
			}
			InputStream is = new FileInputStream(file);
			OutputStream os = new FileOutputStream(imgDist);
			scaleImage(is, os, scale);
			is.close();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		scaleImage("E:/pic/1.bmp", "E:/pic/1-bak.bmp", 80);
	}
}
